package com.fangque.kepp.framework.user.service;


import com.fangque.kepp.framework.user.dao.UserRepository;
import com.fangque.kepp.framework.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 *
 * @author liyk
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserDetailsService {



    @Autowired
    private UserRepository userRepository;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (!optionalUser.isPresent()) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        User user = optionalUser.get();
        return user;
    }

    public User userRegister(String username, String password) {
        //如果用户名存在，返回错误
        Optional<User> byUsername = userRepository.findByUsername(username);
        if (byUsername.isPresent()) {
            return null;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(encode);
        user.setEnabled(true);
        return userRepository.save(user);
    }

//    public List<User> getHrsByKeywords(String keywords) {
//        return userRepository.getHrsByKeywords(keywords);
//    }

/*    public int updateHr(User user) {
        return userRepository.updateHr(user);
    }

    public int updateHrRoles(Long hrId, Long[] rids) {
        int i = userRepository.deleteRoleByHrId(hrId);
        return userRepository.addRolesForHr(hrId, rids);
    }

    public User getHrById(Long hrId) {
        return userRepository.getHrById(hrId);
    }

    public int deleteHr(Long hrId) {
        return userRepository.deleteHr(hrId);
    }

    public List<User> getAllHrExceptAdmin() {
        return userRepository.getAllHr(HrUtils.getCurrentHr().getId());
    }
    public List<User> getAllHr() {
        return userRepository.getAllHr(null);
    }*/
}
